﻿using DotNetExtensions.Core.IOC;
using DotNetExtensions.Core.MVC;
using DotNetExtensions.Core.Restful;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace DotNetExtensions.Core.SqlSugar
{
    [Inject(Scope = InjectScope.Scoped)]
    [AutoInject]
    public class SimpleRepository<TModel, TKey> : BaseRepository<TModel> where TModel : class, new()
    {
        public SimpleRepository(string connectString) : base(connectString)
        {

        }
        public SimpleRepository(string connectString, DbType dbType) : base(connectString, dbType)
        {

        }
        public virtual TModel GetById(TKey key)
        {
            return Model.GetById(key);
        }
        public virtual bool Insert(TModel entity)
        {
            return Model.Insert(entity);
        }
        public virtual bool Insert(List<TModel> entitys)
        {
            return Model.InsertRange(entitys);
        }
        public virtual bool Delete(TKey key)
        {
            return Model.DeleteById(key);
        }
        public virtual bool Update(TModel entity)
        {
            return Model.Update(entity);
        }
        public virtual bool Update(List<TModel> entitys)
        {
            return Model.UpdateRange(entitys);
        }
        public virtual bool Exists(TKey key)
        {
            return Model.GetById(key) != null;
        }
        public virtual bool Exists(Expression<Func<TModel, bool>> expression)
        {
            return Model.AsQueryable().Where(expression).Any();
        }
        public List<TModel> GetAll()
        {
            return Model.GetList();
        }
        public PageResult<TModel> GetPageList(Expression<Func<TModel, bool>> expression, int pageIndex, int pageSize)
        {
            if (pageIndex == 0) pageIndex = 1;
            if (pageSize == 0) pageSize = 40;

            PageResult<TModel> pageResult = new PageResult<TModel>();
            var models = Model.GetPageList(expression, new PageModel { PageIndex = pageIndex, PageSize = pageSize });
            pageResult.Data = models;
            pageResult.Total = Model.Count(expression);

            return pageResult;
        }

        public PageResult<TModel> GetPageList(int pageIndex, int pageSize)
        {
            if (pageIndex == 0) pageIndex = 1;
            if (pageSize == 0) pageSize = 40;

            PageResult<TModel> pageResult = new PageResult<TModel>();
            var models = Model.GetPageList(t => true, new PageModel { PageIndex = pageIndex, PageSize = pageSize });
            pageResult.Data = models;
            pageResult.Total = Model.Count(t => true);

            return pageResult;
        }

    }
}
